#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
#define NUM 1024
namespace client
{

    class tcpclient
{

public:
tcpclient(const string& ip,const uint16_t& port)
:_sock(-1)
,_port(port)
,_ip(ip)
{}

void initclient()
{
//1.创建sockfd
_sock=socket(AF_INET,SOCK_STREAM,0);
if(_sock<0)
{
   cerr<<"socket create error"<<endl;
   exit(2);
}
//2.绑定 ip port，不显示绑定，OS自动绑定
}

void start()
{
struct sockaddr_in ser;
bzero(&ser,sizeof(ser));
socklen_t len=sizeof(ser);
ser.sin_family=AF_INET;
ser.sin_port=htons(_port);
ser.sin_addr.s_addr=inet_addr(_ip.c_str());
if(connect(_sock,(struct sockaddr *)&ser,len)!=0)
{
    cerr<<"connect error"<<endl;
}else
{
    string msg;
    while(true)
    {
        cout<<"Enter# ";
        getline(cin,msg);
        write(_sock,msg.c_str(),msg.size());
        
        char inbuffer[NUM];
        int n=read(_sock,inbuffer,sizeof(inbuffer)-1);
        if(n>0)
        {
            cout<<"server return :"<<inbuffer<<endl;
        }else
        {
            break;
        }
    }
}
}

~tcpclient()
{
    if(_sock>=0) close(_sock);
}

private:
int _sock;
uint16_t _port;
string _ip;

};
}